package captcha

import (
	"bytes"
	"encoding/base64"
	"github.com/dchest/captcha"
	"time"
)

type Config struct {
	Length     int           `help:"验证码长度" default:"4"`
	Weight     int           `help:"验证码图片宽度" default:"120"`
	Height     int           `help:"验证码图片高度" default:"60"`
	CollectNum int           `help:"验证码存储最大数量" default:"100"`
	Expiration time.Duration `help:"验证码过期时间" default:"60s"`
}

type Captcha struct {
	config *Config
}

func NewCaptcha(conf *Config) *Captcha {
	//设置redis为默认保存数据的地方
	captcha.SetCustomStore(captcha.NewMemoryStore(conf.CollectNum, conf.Expiration))
	return &Captcha{config: conf}
}

// Image 获取一个验证码 imageData 存放base64之后的图片信息
func (c *Captcha) Image() (captchaId string, imageData string, err error) {
	captchaId = captcha.NewLen(c.config.Length) //设置验证码长度
	var image bytes.Buffer                      //图片信息保存在bytes.buff里面
	err = captcha.WriteImage(&image, captchaId, c.config.Weight, c.config.Height)
	imageData = base64.StdEncoding.EncodeToString([]byte(image.String()))
	if err != nil {
		return
	}
	return
}

// Verify 验证是否正确 digits 前端传过来的数字字符串验证码
func (c *Captcha) Verify(captchaId string, digits string) bool {
	res := captcha.VerifyString(captchaId, digits)
	if res == false {
		return false
	}
	return true
}
